package com.yc.Testjvm.classfile;

import org.openjdk.jol.info.ClassLayout;

/**
 * 观察对象的内存
 * 参考博客：https://blog.csdn.net/weixin_44141495/article/details/108520566
 */
public class C3 {
    public static void main(String[] args) {
        C3 c = new C3();
//        c.m1();
//        c.m2();
//        c.m3();
//        c.m4();
//        c.m5();
        c.m6();
    }

    /**
     * Object类型对象，对象体为空
     */
    public void m1() {
        Object o = new Object();
        String s = ClassLayout.parseInstance(o).toPrintable();
        System.out.println(s);
    }

    /**
     * Integer类型对象，4字节
     */
    public void m2() {
        Object o = new Integer(2);
        String s = ClassLayout.parseInstance(o).toPrintable();
        System.out.println(s);
    }

    /**
     * Long类型对象：8字节，另外多了4字节的填充，保证8字节倍数
     */
    public void m3() {
        Object o = new Long(2);
        String s = ClassLayout.parseInstance(o).toPrintable();
        System.out.println(s);
    }

    /**
     * markword中的分代年龄
     * 4位，最大15岁
     */
    public void m4() {
        Object o = new Object();
        String s = ClassLayout.parseInstance(o).toPrintable();
        System.out.println(s);
        System.gc();
        s = ClassLayout.parseInstance(o).toPrintable();
        System.out.println(s);
    }

    /**
     * 对象的hashcode只有在调用的时候才会计算出来
     */
    public void m5() {
        Object o = new Object();
        String s = ClassLayout.parseInstance(o).toPrintable();
        System.out.println(s);
        o.hashCode();
        s = ClassLayout.parseInstance(o).toPrintable();
        System.out.println(s);
    }

    /**
     * 观察偏向锁
     */
    public void m6() {
        try {
            Thread.sleep(5000);//jvm启动4秒后才会开启偏向锁
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Object o = new Object();
        synchronized (o){
            System.out.println(ClassLayout.parseInstance(o).toPrintable());
        }
    }

}
